package com.amoby.base.utils;
import java.io.File;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

public class SystemUtil {
    public static String randomUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replaceAll("-", "");
    }

    /**
     * 获取完整的请求根路径
     * 
     * @param request
     * @return
     */
    public static String getRequestRootPath(HttpServletRequest request) {
        String scheme = request.getScheme().toLowerCase();
        int port = request.getServerPort();
        StringBuffer sb = new StringBuffer(scheme);
        sb.append("://").append(request.getServerName());
        if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) {
            sb.append(':').append(port);
        }
        sb.append(request.getContextPath());
        return sb.toString();
    }

    /**
     * 从request获取请求IP
     * 
     * @param request
     * @return
     */
    public static String getRemoteIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static File getWebContextFile(ServletContext servletContext, String path) {
        File file = null;
        file = new File(servletContext.getRealPath(path));
        return file;
    }
}
